#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <pthread.h>
#include <thread>


class ThreadData
{
public:
    ThreadData(const std::string& name,int a,int b):
        _name(name),_a(a),_b(b)
    {

    }
    int Excute()
    {
        return _a + _b;
    }
    std::string Name()
    {
        return _name;
    }
    ~ThreadData()
    {}
private:
    std::string _name;
    int _a;
    int _b;
};

//5.全局变量在线程内部是共享的
int gval = 100;

std::string toHex(pthread_t tid)
{
    //4.进程内的函数,线程共享
    char buffer[64];
    snprintf(buffer,sizeof(buffer),"0x%lx",tid);
    return buffer;
}

void* routine1(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    while(true)
    {
        //3.不加保护的情况下,显示器文件就是共享资源
        std::cout << "我们是新线程,我的名字是: " << td->Name() << 
        ", my tid is : " << toHex(pthread_self()) 
        << ", 全局变量(修改): " << gval<< std::endl;
        gval++;
        std::cout << "task result is : " << td->Excute() << std::endl;
        sleep(1);
        break;
    }
    return 0;
}

int main()
{
    pthread_t tid1;
    ThreadData* td = new ThreadData("thread-1",10,20);
    pthread_create(&tid1,nullptr,routine1,td);

    //线程创建之后,也是要被等待和回收的
    //a. 不等待,类似僵尸进程的问题
    //b. 为了知道新线程的执行结果
    int n = pthread_join(tid1,nullptr);
    if(n != 0)
    {
        std::cerr << "join error: " << n << ", " << strerror(n) << std::endl;
        return 1;
    }
    std::cout << "join success!" << std::endl;
    return 0;
}